package com.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.common.domain.entity.LoginUser;
import com.common.domain.entity.User;
import com.common.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;

/**
 * @author 
 **/
@Service
public class UserDetailsServerImpl implements UserDetailsService {


    @Autowired
    private UserMapper userMapper;

    /**
     * 从数据库中得到用户的信息，进行校验
     * @param userName
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //组装查询条件，得到用户信息
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.eq(User::getUserName, userName);
        User user = userMapper.selectOne(queryWrapper);
        //如果user为空抛出异常
        if(Objects.isNull(user)){
            throw  new RuntimeException("用户不存在");
        }

        return new LoginUser(user,null);
    }
}
